package com.purong.purong.util;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件工具类
 *
 * @author YE
 */
public class FileUtil {

    /**
     * 判断SD是否存在
     *
     * @return
     */
    public static boolean isSdcardExisting() {
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param path 创建路径
     */
    public static void createPath(String path) {
        File file = new File(path);
        if (!file.exists()) {// 判断文件的路径是否存在
            // 按照指定的路径创建文件夹
            file.mkdirs();
        }
    }

    public static File updateDir = null;
    public static File updateFile = null;


    /**
     * byte转MB
     *
     * @param byteSize
     * @return
     */
    public static Double byteToMB(Long byteSize) {
        if (byteSize == null) {
            return 0.0;
        }
        Double doubleSize = (double) (byteSize / 1024 / 1024);
        return doubleSize;
    }

    /**
     * Mb转byte
     *
     * @param doubleSize
     * @return
     */
    public static Long MBtoByte(Double doubleSize) {
        if (doubleSize == null) {
            return (long) 0;
        }
        Long longSize = (long) (doubleSize * 1024 * 1024);
        return longSize;
    }

    public static long getFileSize(String path) {
        if (path == null) {
            return 0;
        }
        File file = new File(path);
        if (file.isDirectory()) {
            return 0;
        }
        return file.length();
    }

    /**
     * 获取目录文件大小
     *
     * @param dir
     * @return
     */
    public static long getDirSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += file.length();
                dirSize += getDirSize(file); // 递归调用继续统计
            }
        }
        return dirSize;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return B/KB/MB/GB
     */
    public static String formatFileSize(long fileS) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    public static Bitmap computeSampleSize(String path){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int height = options.outHeight;
        int width = options.outWidth;
        int reqWidth = 540;
        int reqHeight = 960;
        // 计算缩放比
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            options.inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        Log.e("zwj", "options.inSampleSize=" + options.inSampleSize);
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
    }
    public static File scal(Context context, String path) {
        try {
            if (path==null)
                return null;
            File outputFile = new File(path);
            if (outputFile.exists()) {
                Log.e("zwj", "..........outputFile_exists");
            } else {
                Log.e("zwj", "..........outputFile_noexists");
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            int height = options.outHeight;
            int width = options.outWidth;
            int reqWidth = 540;
            int reqHeight = 960;
            // 计算缩放比
            if (height > reqHeight || width > reqWidth) {
                // 计算出实际宽高和目标宽高的比率
                final int heightRatio = Math.round((float) height / (float) reqHeight);
                final int widthRatio = Math.round((float) width / (float) reqWidth);
                // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
                // 一定都会大于等于目标的宽和高。
                options.inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }
            Log.e("zwj", "options.inSampleSize=" + options.inSampleSize);
            options.inJustDecodeBounds = false;

            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            if (bitmap == null)
                return null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中

            int compress = 100;

            while (baos.toByteArray().length / 1024 > 50 && compress > 40) {//循环判断如果压缩后图片是否大于100kb,大于继续压缩

                baos.reset();//重置baos即清空baos

                compress -= 10;//每次都减少10

                bitmap.compress(Bitmap.CompressFormat.JPEG, compress, baos);//这里压缩options%，把压缩后的数据存放到baos中

            }
            Log.e("zwj", "compress=" + compress);
            outputFile = new File(createImageFile(context, getSuffix(path)).getPath());
            FileOutputStream fos = null;
//            try {
            fos = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, compress, fos);
            fos.close();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }

            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            } else {
                File tempFile = outputFile;
                outputFile = new File(createImageFile(context, getSuffix(path)).getPath());
                copyFileUsingFileChannels(tempFile, outputFile);
            }


            return outputFile;
        } catch (Exception e) {
            return null;
        }


    }

    public static File scal(Context context, String path, int maxSize) {
        Log.e("zwj","....befort_scalpath="+path);
        try {
            if (path==null)
                return null;
            File outputFile = new File(path);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            int height = options.outHeight;
            int width = options.outWidth;
            int reqWidth = 720;
            int reqHeight = 1080;
            // 计算缩放比
            if (height > reqHeight || width > reqWidth) {
                // 计算出实际宽高和目标宽高的比率
                final int heightRatio = Math.round((float) height / (float) reqHeight);
                final int widthRatio = Math.round((float) width / (float) reqWidth);
                // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
                // 一定都会大于等于目标的宽和高。
                options.inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }
            options.inJustDecodeBounds = false;

            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            if (bitmap == null)
                return null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中

            int compress = 100;

            while (baos.toByteArray().length / 1024 > maxSize && compress > 50) {//循环判断如果压缩后图片是否大于100kb,大于继续压缩

                baos.reset();//重置baos即清空baos

                compress -= 10;//每次都减少10

                bitmap.compress(Bitmap.CompressFormat.JPEG, compress, baos);//这里压缩options%，把压缩后的数据存放到baos中

            }
            Log.e("zwj", "compress=" + compress);
            outputFile = new File(createImageFile(context, getSuffix(path)).getPath());
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, compress, fos);
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            } else {
                File tempFile = outputFile;
                outputFile = new File(createImageFile(context, getSuffix(path)).getPath());
                copyFileUsingFileChannels(tempFile, outputFile);
            }

            Log.e("zwj","....after="+outputFile.getAbsolutePath());
            return outputFile;
        } catch (Exception e) {
            return null;
        }
    }

    public static String getSuffix(String picPath) {
        if (picPath.endsWith(".png")) {
            return ".png";
        } else if (picPath.endsWith(".PNG")) {
            return ".PNG";
        } else if (picPath.endsWith(".jpg")) {
            return ".jpg";
        } else if (picPath.endsWith(".JPG")) {
            return ".JPG";
        } else if (picPath.endsWith(".gif")) {
            return ".gif";
        } else if (picPath.endsWith(".GIF")) {
            return ".GIF";
        } else {
            return ".jpg";
        }
    }

    public static Uri createImageFile(Context context, String suffix) {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "Img_" + timeStamp + "_";
        File storageDir = new File(CommonUtil.getDiskCacheDir(context) + "/compress_img");
        if (!storageDir.exists())
            storageDir.mkdirs();
        File image = null;
        try {
            image = File.createTempFile(imageFileName, suffix, storageDir);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Save a file: path for use with ACTION_VIEW intents
        return Uri.fromFile(image);
    }

    public static void copyFileUsingFileChannels(File source, File dest) {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            try {
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } finally {
            try {
                inputChannel.close();
                outputChannel.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static Intent createGetContentIntent() {
        // Implicitly allow the user to select a particular kind of data
        final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // The MIME data type filter
        intent.setType("video/*");
        // Only return URIs that can be opened with ContentResolver
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        return intent;
    }

    //    public static String getPath(final Context context, final Uri uri) {
//
//
//
//        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
//
//        // DocumentProvider
//        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
//            // LocalStorageProvider
//            if (isLocalStorageDocument(uri)) {
//                // The path is the id
//                return DocumentsContract.getDocumentId(uri);
//            }
//            // ExternalStorageProvider
//            else if (isExternalStorageDocument(uri)) {
//                final String docId = DocumentsContract.getDocumentId(uri);
//                final String[] split = docId.split(":");
//                final String type = split[0];
//
//                if ("primary".equalsIgnoreCase(type)) {
//                    return Environment.getExternalStorageDirectory() + "/" + split[1];
//                }
//
//                // TODO handle non-primary volumes
//            }
//            // DownloadsProvider
//            else if (isDownloadsDocument(uri)) {
//
//                final String id = DocumentsContract.getDocumentId(uri);
//                final Uri contentUri = ContentUris.withAppendedId(
//                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
//
//                return getDataColumn(context, contentUri, null, null);
//            }
//            // MediaProvider
//            else if (isMediaDocument(uri)) {
//                final String docId = DocumentsContract.getDocumentId(uri);
//                final String[] split = docId.split(":");
//                final String type = split[0];
//
//                Uri contentUri = null;
//                if ("image".equals(type)) {
//                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//                } else if ("video".equals(type)) {
//                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
//                } else if ("audio".equals(type)) {
//                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//                }
//
//                final String selection = "_id=?";
//                final String[] selectionArgs = new String[]{
//                        split[1]
//                };
//
//                return getDataColumn(context, contentUri, selection, selectionArgs);
//            }
//        }
//        // MediaStore (and general)
//        else if ("content".equalsIgnoreCase(uri.getScheme())) {
//
//            // Return the remote address
//            if (isGooglePhotosUri(uri))
//                return uri.getLastPathSegment();
//
//            return getDataColumn(context, uri, null, null);
//        }
//        // File
//        else if ("file".equalsIgnoreCase(uri.getScheme())) {
//            return uri.getPath();
//        }
//
//        return null;
//    }
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static boolean isLocalStorageDocument(Uri uri) {
        return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {

                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static long getVideoDuration(String path) {
        String duration = "-1";
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();

        try {
            mmr.setDataSource(path);
            duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Long.valueOf(duration);
    }
}
